package com.kamistoat.meimeistore.product.service.impl;

import com.kamistoat.meimeistore.product.vo.AttrGroupRelationVo;
import com.kamistoat.meimeistore.product.dao.AttrAttrgroupRelationDao;
import com.kamistoat.meimeistore.product.entity.AttrAttrgroupRelationEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kamistoat.common.utils.PageUtils;
import com.kamistoat.common.utils.Query;

import com.kamistoat.meimeistore.product.service.AttrAttrgroupRelationService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrAttrgroupRelationService")
public class AttrAttrgroupRelationServiceImpl extends ServiceImpl<AttrAttrgroupRelationDao, AttrAttrgroupRelationEntity> implements AttrAttrgroupRelationService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrAttrgroupRelationEntity> page = this.page(
                new Query<AttrAttrgroupRelationEntity>().getPage(params),
                new QueryWrapper<AttrAttrgroupRelationEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 为属性分组批量新增基础属性关联
     *
     * @param relationVos 关联关系列表
     */
    @Override
    @Transactional
    public void addRelaition(List<AttrGroupRelationVo> relationVos) {
        // 下面这个遍历操作就可以看出，就算在Controller中直接用Entity接收映射也是完全没有问题的。
        relationVos.forEach((relationVo)->{
            // 一个空Entity
            AttrAttrgroupRelationEntity newRelation = new AttrAttrgroupRelationEntity();
            // 先查relation表中是否已经有该数据
            AttrAttrgroupRelationEntity exist = baseMapper.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().
                    eq("attr_id",relationVo.getAttrId()));
            // 若relation数据表中已经存在该属性的行数据，只是其属性分组Id为空，则这里只是更新
            if(exist != null){
                newRelation.setId(exist.getId());
                newRelation.setAttrId(exist.getAttrId());
                newRelation.setAttrGroupId(relationVo.getAttrGroupId());
                this.updateById(newRelation);
            } else {
                // 否则就是直接新增一条relation行数据。
                BeanUtils.copyProperties(relationVo,newRelation);
                this.save(newRelation);
            }
        });
    }
}